<template>
	<div class="index-login p-b-70 propay">
		<div class="main" :style="'background:'+ produInfo.colorList[0]">
			<img :src="baseUrl+produInfo.images[0]" />

			<div id="form"></div>
			<el-form :model="form" :rules="rules" ref="form">
				<el-form-item  prop="mobile">
					<div class="df">
						<el-input v-model.number="form.mobile" placeholder="请输入手机号" @input="handlePhone">
							<span slot="prefix">+86</span>
						</el-input>
						<div class="el-form-item__error" v-if="showError">{{showText}}</div>
					</div>
				</el-form-item>
				<el-form-item  prop="code">
					<el-input v-model="form.code" placeholder="请输入验证码" @input="handleSms" class="sms">
						<el-button @click="getCode" :disabled="timer"  slot="suffix" :style="'background:' + produInfo.colorList[1] + ';border-color:' + produInfo.colorList[1]"> {{ timer ? `${count}秒后重新获取` : '获取验证码' }}</el-button>
					</el-input>
				</el-form-item>
			</el-form>
			<div class="cbtn" @click="submitForm('form',0)" :style="'background:'+ produInfo.colorList[2]">
				<div class="text">立即点击报名</div>
			</div>

			<img :src="baseUrl+item" v-for="(item, index) in produInfo.images" :key="index" v-if="index > 0" />
		</div>
		<div class="footer">
			<div class="price">{{ produInfo.productPrice || 1 }}</div>
			<div class="text" @click="submitForm('form',1)">
				<div class="breathe">立即报名</div>
			</div>
		</div>

		<!-- 支付弹窗 -->
		<!-- <el-drawer title="请选择支付方式" :visible.sync="drawer" direction="btt" :before-close="handleRetain" :wrapperClosable="false">
			<div class="pay-type">
				<div :class="payType == 1 ? 'item on' : 'item'" @click="payType = 1">
					<img src="../../assets/images/icon/alipay.png" alt="">
					<div>支付宝</div>
				</div>
				<div :class="payType == 2 ? 'item on' : 'item'" @click="payType = 2">
					<img src="../../assets/images/icon/weixin.png" alt="">
					<div>微信支付</div>
				</div>
			</div>
			<div class="text-center m-md">
				<el-button round @click="doPay">立即支付</el-button>
			</div>
		</el-drawer> -->

		<!-- 支付挽留 -->
		<!-- <div class="mask" v-if="showRetain">
			<div class="panel">
				<div class="df">
					<div class="btn left" @click="doCancel">残忍离开</div>
					<div class="btn right" @click="doRetain">领取福利</div>
				</div>
			</div>
		</div> -->

		<!-- 支付结果查询 -->
		<div class="mask" v-if="showWxRes">
			<div class="panel panel2">
				<div class="df">
					<div class="btn left" @click="rePay">未支付</div>
					<div class="btn right" @click="reWechat">已支付,添加老师</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import axios from 'axios';
	// import Cookies from 'js-cookie';

	var checkPhone = (rule, value, callback) => {
		const regPhone = /^1[3|4|5|6|7|8|9][0-9]{9}$/
		if (value === '') {
			return callback(new Error('手机号不能为空'))
		} else if (!regPhone.test(value)) {
			callback(new Error('请输入正确的手机号'))
		} else {
			callback()
		}
	};

	export default {
		data () {
			return {
				productId:1,
				produInfo:{},
				imagesList:[],
				baseUrl:`${this.$siteURL}/imgs/mini/`,
				pathId:'',//投放平台pathid
				timer:false,
				count: 60,
				showText:'',
				showError:false,
				form: {
					code:'',
					mobile: ''
				},
				rules: {
					code:[{ required: true, message: '请输入验证码', trigger: 'blur' }],
					mobile: [
						{ required: true, message: '请输入手机号', trigger: 'blur' },
						{ validator: checkPhone, trigger: 'blur' }
					]
				},
				phoneLcok:false,//手机输入埋点
				smsLock:false,
				// payType: 2,
				// drawer: false,
				// showRetain:false,
				wxPoll: null,
				showWxRes: false
			}
		},
		created(){
			this.form.mobile = this.form.mobile || this.$store.state.userPhone || ''
			this.productId = this.$route.query.productId || 1   //产品ID
			this.$route.query.channels.indexOf('ss') > 0 || this.$route.query.channels.indexOf('tl') > 0 ? this.gosslBD() : this.goxxlBD()
			this.getProduct()
		},
		methods:{
			recastUrl(){
				let url = window.location.href,path
				//不允许分享报名
				// let vHash = url.indexOf('/#/product')//判断hash是否被拆分
				// if(vHash < 0){
				// 	let v1 = url.split('/?')[0]
				// 	let v2 = url.split('#/')[1]
				// 	let newUrl = v1 + '/#/' + v2
				// 	path = encodeURIComponent(newUrl)
				// }else{
				// 	path = encodeURIComponent(url)
				// }
				path = encodeURIComponent(url)
				return path
			},
			// 回传百度id-xxl适用
			goxxlBD(){
				let path = this.recastUrl()
				axios({
					method:"GET",
					url:`${this.$baseURL}/getPutIndex`,
					params:{
						putIndex: path
					}
				}).then(res => {
					this.pathId = this.$route.query.bd_vid
					this.$store.commit("SET_PATHID", this.pathId)
				})
      		},
			// 回传百度id-ss搜索适用，tl投流适用
			gosslBD(){
				let path = this.recastUrl()
				axios({
					method:"GET",
					url:`${this.$baseURL}/getPutIndexssl`,
					params:{
						putIndex: path
					}
				}).then(res => {
					this.pathId = res.data.message
					this.$store.commit("SET_PATHID", this.pathId)
				})
      		},
      		getProduct(){
				axios({
					method:'GET',
					url: `${this.$baseURL}/queryProductInfo`,
					params:{
						productId: this.productId
					}
				}).then(res => {
					this.produInfo = res.data
					this.produInfo.colorList = res.data.theme && res.data.theme.indexOf(',') > 0 ? res.data.theme.split(',') : ['#fff','#1ACE9A','#1ACE9A']
				})
			},
			handlePhone(val){  
				if(val.length > 6){
					if(this.phoneLcok){
						return false
					}
					this.phoneLcok  = true
					let that = this
					setTimeout(() => {
						that.phoneLcok  = false
						that.doPoint('ecEnterPhone',0)//埋点
					},2000)
				}else{
					this.phoneLcok  = false
				}
			},
			handleSms(val){
				this.form.code = val.slice(-6)
				if(this.smsLock){
					return
				}
				this.smsLock = true
				this.doPoint('ecEnterCode',0)//埋点
			},
			//获取短信验证码
			getCode(){
				if(!this.form.mobile){
					this.showError = true
					this.showText = '请输入手机号'
					return false
				}
				const regPhone = /^1[3|4|5|6|7|8|9][0-9]{9}$/
				if(!regPhone.test(this.form.mobile)){
					this.showError = true
					this.showText = '请输入正确的手机号'
					return false
				}
				this.showError = false

				this.doPoint('ecGetCode',0)//埋点
				axios({
					method:"GET",
					url:`${this.$baseURL}/sms`,
					params:{
						phone: this.form.mobile
					}
				}).then(res => {
					if(res.data.code == 0){
						this.countDown()
					}else{
						this.$message({
							message: res.data.msg,
							type: 'warning'
						})
					}
				})
			},
			//短信定时器
			countDown(){
				if(this.count > 0){
					this.timer = true
					setTimeout(() => {
						this.count--
						this.countDown()
					},1000)
				}else{
					this.timer = false
					this.count = 60
				}
			},
			submitForm(formName,val) {
				this.showError = false
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.doPoint('ecApplyNow',val)
						this.login()
					} else {
						window.scrollTo({
							top:150,
							behavior:'smooth'
						})
						return false
					}
				});
			},
			login(){
				axios({
					method:"POST",
					url:`${this.$baseURL}/userLoginSmsVerify`,
					params:{
						userPhone: this.form.mobile,
						code: this.form.code,
						productId: this.productId,
						pathId: this.pathId
					}
				}).then(res => {
					if(res.data.code == 200){
						this.doPoint('ecUpPayment',0)
						this.wechatPay()
					}else if(res.data.code == 1004){
						this.wechatOpen(0,1)
					}else{
						this.$message({message: res.data.message});
					}
				})
			},
			//支付弹窗-未支付
			rePay(){
				this.showWxRes = false
				this.doPoint('ecNonPayment',0)
				clearInterval(that.wxPoll)
			},
			//支付弹窗-已支付
			reWechat(){
				this.wechatOpen(1,1)
				this.doPoint('ecNonPayment',1)
			},
			//微信支付
			wechatPay(){
				this.doPoint('ecPaymentMethod',1)
				this.$store.commit("SET_PHONE", this.form.mobile)
				let that = this
				setTimeout(() => {
					that.showWxRes = true
				},2500)
				let num = (this.produInfo.productPrice * 100).toFixed(0)
				axios({
					method:"GET",
					url:`${this.$baseURL}/v3/h5Pay`,
					params: {
						pathId: this.pathId,
						userPhone: this.form.mobile,
						productId: this.productId,
						productName: this.produInfo.productName,
						price: num
					}
				}).then(res => {
					// 方案一： 支付中间页-待定需求
					// let url = `${this.$siteURL}/#/pay/wxres?phone=${this.form.mobile}&pathId=${this.pathId}&productId=${this.productId}`
					// let path = res.data + '&redirect_url=' + encodeURIComponent(url)
					// this.showWxRes = true
					// window.location.href = path

					//方案二：本地调起
					this.wxPolling ()
					let that = this
					setTimeout(() => {
						clearInterval(that.wxPoll)
					},180000)
					window.location.href = res.data
				})
			},
			wxPolling(){
				this.wxPoll = setInterval(() => {
					this.wechatOpen(1,0)
				},1000)
			},
			//打开获客链接 type=0,不下发短信;type=1,下发短信。showMsg=0,不展示信息，showMsg=1展示信息
			wechatOpen(type,showMsg){
				const phone = this.form.mobile || this.$store.state.userPhone
				axios({
					method:"POST",
					url:`${this.$baseURL}/getWechatIndexClass`,
					params: {
						userPhone: phone
					}
				}).then(res => {
					if(res.data.code == 200){
						clearInterval(this.wxPoll)
						let data = res.data.data
						if(type == 1){
							this.custSms(data.class_id,data.class_user_id)
						}
						window.location.href = data.class_wechat_index + '?customer_channel=' + data.class_id + '_H5' + '_' + this.productId
					}else{
						if(showMsg == 1){
							this.$message({message: '支付失败或未查到支付结果'});
						}
					}
				})
			},
			//下发客户短信
			custSms(id,wx){
				axios({
					method:"POST",
					url:`${this.$backend}/customer_acquisition/send_signup_sms`,
					data: {
						"class_id": id,
    					"wx_user_id":wx
					}
				}).then(res => {
					console.log(res)
				})
			},
			//埋点
			doPoint(type,val){
				let params = {
					clickId: this.pathId,
					productId: this.productId,
					[type] : val
				}
				axios({
					method:"POST",
					url:`${this.$baseURL}/insertApplyEc`,
					params: params
				}).then(res => {
					if(res.data.code !== 200){
						console.log(res.data.message)
					}
				})
			},
		}
	}
</script>


<style scoped>
	.footer{background-image: url('./../../assets/images/btn2.png');}
	.price{color: #ff4242;position: absolute;left: 20px;bottom: 8px;font-size: 42px;font-weight: bold;}

	.pay-type{display: flex;justify-content: space-around;}
	.pay-type .item{text-align: center;background: #F2F2F2;font-size: 18px;color: #333;;width: 35%;padding: 15px;border-radius: 10px;border: 1px solid #F2F2F2;}
	.pay-type .item.on{background: #F6E5E5;border-color: #FF0000;}
	.pay-type .item img{width: 35px;height: 35px;}
	.el-button.is-round{width: 100%;background: linear-gradient(90deg, #ff4242 0%, #ff7e18 100%);border: none;color: #fff;font-size: 20px;}
	
	.panel{background: url(../../assets/images/retain.png) no-repeat;width: 100%;height: 82vw;background-size: cover;    margin-top: 40%;position: relative;}
	.panel .df{position: absolute;bottom: 0;left: 0;right: 0;justify-content: center;}
	.panel .btn{padding: 10px 20px;border-radius: 10px;margin: 20px 15px 40px;font-size: 20px;font-weight: bold;}
	.panel .left{color: #7D2500;border: 1px solid #7D2500;}
	.panel .right{color: #fff;background: linear-gradient(90deg, #FF0000 0%, #FF7200 100%);}

	.panel2{background-image: url(../../assets/images/pay.png);border-radius: 20px;width: calc(100% - 30px);height: 96vw;margin-left: auto;margin-right: auto;max-height: 666px;max-width: 641px;}
	.panel2 .btn{padding: 10px;margin: 20px 10px;font-weight: normal;}

	.cbtn{margin: 20px 30px 0px;padding: 18px 25px;background: #1ACE9A;text-align: center;border-radius: 35px;margin-bottom: 20px;}
	.cbtn .text{animation: testAnimation 1.5s linear infinite;color: #fff;font-size: 1.5rem;letter-spacing: 2px;font-weight: bold;cursor: pointer;}
	/* css3 */
	@keyframes testAnimation {
		0%{
			transform: scale(.9);
		}
		50%{
			transform: scale(1.2);
		}
		100%{
			transform: scale(.9);
		}
	}

	@media screen and (min-width:740px){
		.price{font-size: 90px;bottom:15px;}
	}
</style>
